using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.Threading;

namespace SlamCms.SharePoint.FieldTypes.Features
{
	[Guid("efca2acf-2b96-4845-87ca-adddda6629cc")]
	public class FieldTypesEventReceiver : SPFeatureReceiver
	{	
		private static string _owner = "SlamFieldTypes";
		private SPWebConfigModification[] _modifications = {
				new SPWebConfigModification() { 
				Name = "add[@assembly='CKEditor.NET, Version=3.6.4.0, Culture=neutral, PublicKeyToken=e379cdf2f8354999']", 
				Owner = _owner, 
				Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode, 
				Path = "/configuration/system.web/compilation/assemblies", 
				Value = "<add assembly=\"CKEditor.NET, Version=3.6.4.0, Culture=neutral, PublicKeyToken=e379cdf2f8354999\" />"}

		};

		public override void FeatureActivated(SPFeatureReceiverProperties properties)
		{
			SPWebApplication application = (SPWebApplication)properties.Feature.Parent;

			foreach (SPWebConfigModification modification in _modifications)
			{
				application.WebConfigModifications.Add(modification);
			}

			application.WebService.ApplyWebConfigModifications();
			application.Update();
			Thread.Sleep(1000);
		}

		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			SPWebApplication application = (SPWebApplication)properties.Feature.Parent;

			List<SPWebConfigModification> modificationsToRemove = new List<SPWebConfigModification>();
			foreach (SPWebConfigModification modification in application.WebConfigModifications)
			{
				if (modification.Owner == _owner)
				{
					modificationsToRemove.Add(modification);
				}
			}

			foreach (SPWebConfigModification modification in modificationsToRemove)
			{
				application.WebConfigModifications.Remove(modification);
			}

			application.WebService.ApplyWebConfigModifications();
			application.Update();
			Thread.Sleep(1000);
		}
	}
}
